const COLLECTIONS = ["mall_product","mall_shop_car","mall_order_info","mall_order_detail"]
App({
  globalData: {
    userInfo: null,
  },
 async onLaunch(options) {
  let resolve;
   this.data = {
     wait: new Promise((resolve1) => {
       resolve = resolve1
     })
   };
    //初始化function调用，修改为自己的环境 ID
    const context = await my.cloud.createCloudContext({
      env: 'env-00jxt5mhgfdx'
    });
    await context.init();
    my.fncontext = context;
    //使用function的方式进行初始化，两中方式取其中一个方式就可以，用户可以使用自己合适的方式。
    my.getCloudContext  = async function(){
      if(my.fncontext){
        return  my.fncontext;
      }else{
        const context = await my.cloud.createCloudContext({
          env: 'env-00jxt5mhgfdx'
        });

        await context.init();
        my.fncontext = context;
      }
      return my.fncontext;
    },
    this.getUserInfo();
    this.initeCollection();
    resolve();
  },
  onShow(options) {

  },
  //这个初次加载存在获取不到userinfo问题,升级ide版本之后没复现了
  async getUserInfo() {
     my.getAuthCode({
      scopes: 'auth_user',
      fail: (error) => {
        console.error('getAuthCode', error);
      },
      success: ({
        authCode
      }) => {
        // do login...
        // then
        console.log(`authCode:`, authCode);
        // var context = await my.getCloudContext();
        const response =  my.fncontext.callFunction({
          name: 'AlipayUserInfo',
          data: {
            auth_code: authCode
          },
        }).then(({
          result: userInfo
        }) => {
          console.log(`userInfo:`, userInfo);
          // 将 nick_name 改为 nickName
          userInfo.nickName = userInfo.nick_name;
          delete userInfo.nick_name;
          //设置全局变量
          const app = getApp();
          app.globalData.userInfo = userInfo;
        }).catch(error => {
          console.error('getAuthUserInfo', error);
        });
        return response;
      }
    });
  },
  async initeCollection(){
    const response =  await my.fncontext.callFunction({
      name: 'mallInitialize',
      data: {
        collections: COLLECTIONS
      },
    })
    console.log(`response:`, response);
  }
});
